<template>
  <div class="perception_add">
    <el-input v-model="title" clearable placeholder="请输入文章标题"></el-input>
    <Wangeditor style="margin: 10px 0;" @get_html="getevent"></Wangeditor>
    <el-button @click="fabu" :loading="fabuFlag" style="margin-right: 40px">{{ fabuval }}</el-button><el-checkbox v-model="overt">公开文章</el-checkbox>
  </div>
</template>

<script>
import Wangeditor from "../../components/Wangeditor"
import qs from "qs";
import {addArticle, delImgArticle} from "../../utils/api";
import {mapState} from 'vuex';
export default {
  name: "PerceptionAdd",
  data(){
    return {
      title:'',
      editor:'',
      isfabu:false,
      imgArray:[],
      overt:true,
      fabuval:'发布',
      fabuFlag:false,
      chirldEditor:null,
    }
  },
  computed:{
    ...mapState([
        "userid"
    ])
  },
  methods:{
    fabu(){
      if(!this.title){
        this.$message.error("标题还没写呢")
        return
      }
      if(!this.editor){
        this.$message.error("还没写内容呢")
        return
      }

      this.fabuFlag=true
      this.fabuval = '发布中'

      //查找出被删除的图片
      let delimg = this.getNewArr(this.chirldEditor.getElemsByType('image')?.map(v=>v?.src),this.imgArray)
      if(delimg.length>0){
        //删除图片
        delImgArticle(qs.stringify({imgsrc: JSON.stringify(delimg)})).then(_res=>{
          if(_res.status==200){
            localStorage.removeItem('shanchutupian')
          }
        }).catch()
      }

      /*判断该用户是否为当日首次发布*/
      let day = 0
      let localStorageValue = localStorage.getItem('dailyRelease')
      if(!localStorageValue){
        day = 1
      }else{
        if(new Date().getDate()!=new Date(localStorageValue-0).getDate()){
          day = 1
        }else{
          /*同一天 进一步判断是否为当天*/
          let _time = new Date()
          if(!(localStorageValue-0>=new Date(_time.setDate(_time.getDate())).setHours(0,0,0,0) && localStorageValue-0<new Date(_time.setDate(_time.getDate()+1)).setHours(0,0,0,0))){
            day = 1
          }
        }
      }

      addArticle(qs.stringify({body:this.editor,title:this.title,id:this.userid,overt:this.overt?0:1,day})).then(respose=>{
        this.fabuFlag=false
        if(respose.status===200){
          this.fabuval = '发布成功'
          this.isfabu=true;
          localStorage.removeItem("fabutupian")
          if(respose.wxdaily){
            if(respose.wxdaily!=0){
              this.$notify({
                title: '发布成功',
                message: `获得奖励￥${respose.wxdaily}元`,
                type: 'success'
              });
            }
            localStorage.setItem('dailyRelease',new Date().getTime()+'')
          }else{
            this.$notify({
              title: '成功',
              message: '发布成功',
              type: 'success'
            });
          }
          this.$router.replace({name:'perceptionlook',query:{id:respose?.id,add:"1"}})
        }else{
          this.fabuval = '发布失败,点击重新发布';
          this.$notify.error({
            title: '出错啦/(ㄒoㄒ)/~~',
            message: respose?.msg,
          });
        }
      }).catch(error=>{
        console.log(error);
      })
    },
    getevent(v,editor,allimg,newImg){
      this.editor=v;
      this.chirldEditor = editor //editor.getElemsByType('image')?.map(v=>v.src)
      this.imgArray=allimg;
      let nowimg = this.chirldEditor.getElemsByType('image')?.map(v=>v?.src)
      let delimg = this.getNewArr(nowimg,this.imgArray)
      if(delimg.length>0){
        localStorage.setItem('shanchutupian',delimg)
      }
    },
    getNewArr(a, b) {
      const arr = [...a, ...b];
      const newArr = arr.filter(item => {
        return !(a.includes(item) && b.includes(item));
      });
      return newArr;
    },
  },
  components:{
    Wangeditor
  },
  beforeRouteLeave(to, from,next) {
    if(!this.isfabu && (this.chirldEditor.getText() || this.imgArray.length>0)){ //没有发布成功 并且 有内容
      this.$dialog.confirm({
        title: '提示',
        message:'你还没有发布文章, 离开后将不保存内容，是否确定离开',
      }).then(() => {
        /*不发布 离开页面*/
        if(this.imgArray.length!==0){
          /*如果没有图片就不发送请求*/
          delImgArticle(qs.stringify({imgsrc: JSON.stringify(this.imgArray)})).then(respose=>{
            /*删除成功 清空缓存*/
            if(respose.status===200){
              localStorage.removeItem("fabutupian");
            }
          }).catch(error=>{
            console.log(error);
          })
        }
        next(true);
      }).catch(() => {
        next(false);
      });
    }else{
      next(true);
    }
  },
}
</script>

<style scoped>
.perception_add{
  padding: 10px
}
.el-message-box{
  width: 300px!important;
}

</style>
